<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/14
 * Time: 14:43
 */

namespace Home\Controller;
use Think\Controller;

class SmsController extends Controller {

    public $api_account;
    public $api_password;
    public $api_send_url;

    public function __construct()
    {
        parent::__construct();
        $this->api_account = '98a169';//短信平台的appid
        $this->api_password = 'qxhav58zln';//短信平台的appkey
        $this->api_send_url = 'http://api.chanzor.com/send';//接口请求地址
    }

    /*
     * 传入手机号和发送短信的类型调用接口发送短信并写入数据库
     * @param string $mobile //手机号码
     * @param int $type 为1时发送注册验证短信，为2时发送找回密码验证短信，为3身份认证失败，为4提醒进行身份认证，为5提醒心动，6长期不登录提醒
     * @param return //发送成功有返回值，失败没有返回值
     */
    public function send_sms($mobile,$type)
    {
        $model = M('sms');
        $code = rand(1000,9999);
        if($type==1||$type==2)
        {
            $content = "微恋验证码为" . $code . "%20【WE%20LOVE】";
        }else if($type==4)
        {
            $content = "您已注册成功，距离爱情仅差一步认证。官网：www.520welove.com%20【WE LOVE】";
        }
        else if($type==5)
        {
            $content = "哇，有人对你心动了，快来看看是不是你的那个TA。官网：www.520welove.com%20【WE LOVE】";
        }
        $sendTime = '';
        $url = 'http://api.chanzor.com/send?account='.$this->api_account.'&password='.$this->api_password.'&mobile='.$mobile.'&content='.$content.'&sendTime='.$sendTime;
        $html = $this->curlGet($url);
        $result = json_decode($html,true);
       if($result['status']==0)
       {
           $data = array(
               'mobile'=>$mobile,
               'code'=>$code,
               'content'=>$content,
               'type'=>$type,
               'send_time'=>date('Y-m-d H:i:s',time()),
           );
           $res = $model->data($data)->add();
           if(!empty($res))
               return $code;
       }else{
           return false;
       }
    }

    /*
     * curl函数模拟get请求
     * @param string $url //get请求的地址
     * @param json $file_contents //get请求返回的参数
     */
    public function curlGet($url)
    {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt ($ch, CURLOPT_URL,$url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }

}